<template>
  <view class="logistics-container">
    <!-- 顶部导航栏 -->
    <view class="logistics-header">
      <button @click="navigateBack" class="back-btn">
        <i class="fa fa-arrow-left"></i>
      </button>
      <text class="title">物流信息</text>
      <view class="empty-box"></view>
    </view>
    
    <!-- 物流参数展示区域 -->
    <view class="logistics-info">
      <view class="info-item">
        <text class="label">订单ID：</text>
        <text class="value">{{ orderId }}</text>
      </view>
      <view class="info-item">
        <text class="label">发货时间：</text>
        <text class="value">{{ deliveryTime || '暂无数据' }}</text>
      </view>
      <view class="info-item">
        <text class="label">商家信息：</text>
        <text class="value">{{ shopAddr }}</text>
      </view>
      <view class="info-item">
        <text class="label">收货人：</text>
        <text class="value">{{ receiveName }}</text>
      </view>
      <view class="info-item">
        <text class="label">联系电话：</text>
        <text class="value">{{ formatPhone(receiveMobile) }}</text>
      </view>
      <view class="info-item">
        <text class="label">收货地址：</text>
        <text class="value">{{ receiveAddr }}</text>
      </view>
    </view>

    <!-- 百度地图容器 -->
    <view class="map-container">
      <view class="map-title">配送路线</view>
      <view id="baiduMap" class="map-wrapper"></view>
      <button class="nav-btn" @click="openNavigation">
        点击导航
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 物流参数（接收自order页面）
	  ak: 'H4YdFbkDBIbCvaNBsbrFRSlvxEjCHCvC',
      orderId: '',
      deliveryTime: '',
      shopAddr: '', // 商家地址文字（需转换为经纬度）
      receiveName: '',
      receiveMobile: '',
      receiveAddr: '',
      receiveLng: 0, // 收货经度（已有）
      receiveLat: 0, // 收货纬度（已有）
      
      // 转换后的商家经纬度（初始为空）
      shopLng: 0,
      shopLat: 0,
	  
	  shopPoint: null, // 商家地址转换后的坐标
	  receivePoint: null, // 收货地址转换后的坐标
      
      map: null,
      driving: null
    };
  },
  onLoad(options) {
    // 接收参数（仅接收已有数据）
    this.orderId = options.orderId || '';
    this.deliveryTime = options.deliveryTime || '';
    this.shopAddr = options.shopAddr || ''; // 商家地址文字
    this.receiveName = options.receiveName || '';
    this.receiveMobile = options.receiveMobile || '';
    this.receiveAddr = options.receiveAddr || '';
    this.receiveLng = parseFloat(options.receiveLng) || 0;
    this.receiveLat = parseFloat(options.receiveLat) || 0;
	
	this.shopLng = parseFloat(options.shopLng) || 0;
	this.shopLat = parseFloat(options.shopLat) || 0;
	// 关键：先将商家地址和收货地址转换为经纬度
	  this.convertAddressToPoint(this.shopAddr, 'shop'); // 转换商家地址
	  this.convertAddressToPoint(this.receiveAddr, 'receive'); // 转换收货地址
	// console.log('接收的商家经纬度：', this.shopLng, this.shopLat);
	// console.log('接收的收货经纬度：', this.receiveLng, this.receiveLat);
    // 加载百度地图SDK（加载完成后转换商家地址）
    this.loadBaiduMapSDK();
  },
  methods: {
	  convertAddressToPoint(address, type) {
	      if (!window.BMap || !address) return;
	      
	      const myGeo = new BMap.Geocoder();
	      myGeo.getPoint(
	        address,
	        (point) => {
	          if (point) {
	            console.log(`${type}地址转换成功：`, point.lng, point.lat);
	            if (type === 'shop') {
	              this.shopPoint = point; // 商家坐标
	            } else {
	              this.receivePoint = point; // 收货坐标
	            }
	            // 两个地址都转换完成后，初始化地图
	            if (this.shopPoint && this.receivePoint) {
	              this.initMapByAddress();
	            }
	          } else {
	            console.error(`${type}地址转换失败：${address}`);
	            uni.showToast({ title: `${type === 'shop' ? '商家' : '收货'}地址解析失败`, icon: 'none' });
	          }
	        },
	        // 优化：指定城市（减少解析错误，如商家地址在郑州，收货在深圳）
	        type === 'shop' ? '郑州市' : '深圳市'
	      );
	    },
	    
	    // 新增：基于地址转换的坐标初始化地图
	    initMapByAddress() {
	      if (!this.shopPoint || !this.receivePoint) return;
	      
	      this.map = new BMap.Map("baiduMap");
	      // 中心点设为两地中点
	      const centerPoint = new BMap.Point(
	        (this.shopPoint.lng + this.receivePoint.lng) / 2,
	        (this.shopPoint.lat + this.receivePoint.lat) / 2
	      );
	      this.map.centerAndZoom(centerPoint, 6); // 缩放级别设为6（适合跨城市）
	      
	      // 添加控件
	      this.map.addControl(new BMap.NavigationControl());
	      this.map.addControl(new BMap.ScaleControl());
	      
	      // 添加标记和路线
	      this.addMarkersByAddress();
	      this.drawRouteByAddress();
	    },
	    
	    // 新增：基于地址坐标添加标记
	    addMarkersByAddress() {
	      // 商家标记
	      const shopMarker = new BMap.Marker(this.shopPoint);
	      this.map.addOverlay(shopMarker);
	      shopMarker.setTitle('商家位置');
	      shopMarker.addEventListener('click', () => {
	        this.map.openInfoWindow(new BMap.InfoWindow(`商家：${this.shopAddr}`), this.shopPoint);
	      });
	      
	      // 收货标记
	      const receiveMarker = new BMap.Marker(this.receivePoint);
	      this.map.addOverlay(receiveMarker);
	      receiveMarker.setTitle('收货地址');
	      receiveMarker.addEventListener('click', () => {
	        this.map.openInfoWindow(new BMap.InfoWindow(`收货人：${this.receiveName}\n地址：${this.receiveAddr}`), this.receivePoint);
	      });
	    },
	    
	    // 新增：基于地址坐标绘制路线
	    drawRouteByAddress() {
	      const driving = new BMap.DrivingRoute(this.map, {
	        renderOptions: { map: this.map, autoViewport: true },
	        onSearchComplete: (results) => {
	          if (driving.getStatus() !== BMAP_STATUS_SUCCESS) {
	            console.warn('路线规划失败，显示直线距离');
	            const polyline = new BMap.Polyline(
	              [this.shopPoint, this.receivePoint],
	              { strokeColor: "#007aff", strokeWeight: 4, strokeOpacity: 0.8 }
	            );
	            this.map.addOverlay(polyline);
	          }
	        }
	      });
	      driving.search(this.shopPoint, this.receivePoint);
	    },
	  
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    },
    
    // 加载百度地图SDK
    loadBaiduMapSDK() {
      if (window.BMap) {
        this.convertShopAddrToLngLat(); // SDK已加载，直接转换地址
        return;
      }

      const ak = 'H4YdFbkDBIbCvaNBsbrFRSlvxEjCHCvC'; // 你的百度Key
      const script = document.createElement('script');
      script.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=initMap`;
      script.async = true;

      // 全局回调：SDK加载完成后转换商家地址
      window.initMap = () => {
        console.log('百度地图SDK加载完成');
        this.convertShopAddrToLngLat();
      };

      script.onerror = () => {
        console.error('地图SDK加载失败');
        uni.showToast({ title: '地图加载失败', icon: 'none' });
      };

      document.head.appendChild(script);
    },
    
    // 核心：将商家地址文字转换为经纬度（地理编码）
    // 修改 convertShopAddrToLngLat 方法
    convertShopAddrToLngLat() {
      if (!window.BMap || !this.shopAddr) {
        console.error('地址转换条件不足');
        return;
      }
    
      const myGeo = new BMap.Geocoder();
      // 优化1：提取纯地址（去除店铺名等冗余信息）
      const pureShopAddr = this.shopAddr.replace(/^(店铺|公司|商家)\s*/, ''); 
      // 优化2：强制拼接城市名（确保解析在郑州）
      const addrWithCity = `郑州市${pureShopAddr}`;
    
      myGeo.getPoint(
        addrWithCity,
        (point) => {
          if (point) {
            this.shopLng = point.lng;
            this.shopLat = point.lat;
            console.log('商家地址解析成功：', point.lng, point.lat);
            // 验证解析是否在郑州（郑州经纬度范围：lng 112.4-114.2，lat 34.1-34.9）
            if (point.lng < 112.4 || point.lng > 114.2 || point.lat < 34.1 || point.lat > 34.9) {
              console.warn('地址解析偏离郑州市，使用默认坐标');
              this.shopLng = 113.6654; // 郑州二七区中心经度
              this.shopLat = 34.7579;  // 郑州二七区中心纬度
            }
            this.initBaiduMap();
          } else {
            console.error('地址解析失败，使用默认坐标');
            // 失败时强制使用郑州二七区坐标
            this.shopLng = 113.6654;
            this.shopLat = 34.7579;
            this.initBaiduMap();
          }
        },
        '郑州市' // 严格限定城市
      );
    },
    
    // 初始化地图（使用转换后的商家坐标和已有收货坐标）
    initBaiduMap() {
      if (!window.BMap) return;

      this.map = new BMap.Map("baiduMap");

      // 商家坐标（转换后）和收货坐标（已有）
      const shopPoint = new BMap.Point(this.shopLng, this.shopLat);
      const receivePoint = new BMap.Point(this.receiveLng, this.receiveLat);

      // 地图中心点为两地中点
      const centerPoint = new BMap.Point(
        (shopPoint.lng + receivePoint.lng) / 2,
        (shopPoint.lat + receivePoint.lat) / 2
      );
      this.map.centerAndZoom(centerPoint, 10);

      // 添加控件
      this.map.addControl(new BMap.NavigationControl());
      this.map.addControl(new BMap.ScaleControl());

      // 添加标记和路线
      this.addMarkers(shopPoint, receivePoint);
      this.drawRoute(shopPoint, receivePoint);
    },
    
    // 添加标记点（使用真实地址）
    // 修改 addMarkers 方法，使用自定义图标
    addMarkers(shopPoint, receivePoint) {
      // 1. 商家起点：使用 static-marker.png
      // 注意：图标路径需根据实际存放位置调整（此处假设放在 /static/images/ 目录下）
      const shopIcon = new BMap.Icon(
        '/static/shop-marker.png', // 商家图标路径
        new BMap.Size(30, 30), // 图标尺寸（宽x高，根据实际图片调整）
        { 
          anchor: new BMap.Size(15, 30), // 图标锚点（中心点下方，确保标记点对准坐标）
          imageSize: new BMap.Size(30, 30) // 实际显示尺寸（与上面保持一致）
        }
      );
      const shopMarker = new BMap.Marker(shopPoint, { icon: shopIcon });
      this.map.addOverlay(shopMarker);
      shopMarker.setTitle('商家位置');
      shopMarker.addEventListener('click', () => {
        this.map.openInfoWindow(new BMap.InfoWindow(`商家：${this.shopAddr}`), shopPoint);
      });
    
      // 2. 用户终点：使用 user-marker.png
      const receiveIcon = new BMap.Icon(
        '/static/user-marker.png', // 用户图标路径
        new BMap.Size(30, 30), // 图标尺寸（根据实际图片调整）
        { 
          anchor: new BMap.Size(15, 30), // 图标锚点（确保标记点对准坐标）
          imageSize: new BMap.Size(30, 30)
        }
      );
      const receiveMarker = new BMap.Marker(receivePoint, { icon: receiveIcon });
      this.map.addOverlay(receiveMarker);
      receiveMarker.setTitle('收货地址');
      receiveMarker.addEventListener('click', () => {
        this.map.openInfoWindow(new BMap.InfoWindow(`收货人：${this.receiveName}\n地址：${this.receiveAddr}`), receivePoint);
      });
    },
    
    // 绘制路线
    // 修改 drawRoute 方法
    drawRoute(shopPoint, receivePoint) {
      if (shopPoint.lng === 0 || receivePoint.lng === 0) {
        console.error('经纬度无效');
        return;
      }
    
      // 使用驾车路线规划（支持跨城市）
      this.driving = new BMap.DrivingRoute(this.map, {
        renderOptions: { map: this.map, autoViewport: true },
        onSearchComplete: (results) => {
          if (this.driving.getStatus() !== BMAP_STATUS_SUCCESS) {
            console.warn('路线规划失败，显示直线距离');
            // 绘制直线 fallback
            const polyline = new BMap.Polyline(
              [shopPoint, receivePoint],
              { strokeColor: "#007aff", strokeWeight: 4, strokeOpacity: 0.8 }
            );
            this.map.addOverlay(polyline);
          }
        }
      });
      this.driving.search(shopPoint, receivePoint);
    },
    
    // 打开导航
   // 修改：点击导航按钮时，基于地址重新规划路线
     openNavigation() {
       if (!this.shopAddr || !this.receiveAddr) {
         uni.showToast({ title: '地址信息不完整', icon: 'none' });
         return;
       }
       
       // 再次确认地址转坐标（避免初始化失败的情况）
       this.convertAddressToPoint(this.shopAddr, 'shop');
       this.convertAddressToPoint(this.receiveAddr, 'receive');
       
       // 延迟执行，确保坐标转换完成
       setTimeout(() => {
         if (this.shopPoint && this.receivePoint) {
           // 调用后端转发接口，基于地址转换的坐标获取路线
           const origin = `${this.shopPoint.lng},${this.shopPoint.lat}`;
           const destination = `${this.receivePoint.lng},${this.receivePoint.lat}`;
           const ak = this.ak;
           const backendUrl = `http://localhost:3000/api/baidu/direction?origin=${origin}&destination=${destination}&ak=${ak}`;
           
           uni.request({
             url: backendUrl,
             method: 'GET',
             success: (res) => {
               const data = res.data;
               if (data.status === 0 && data.result?.routes?.length > 0) {
                 uni.navigateTo({
                   url: `/pages/navigation/detail?route=${encodeURIComponent(JSON.stringify(data.result.routes[0]))}`
                 });
               } else {
                 uni.showToast({ title: '获取导航路线失败', icon: 'none' });
               }
             }
           });
         } else {
           uni.showToast({ title: '地址解析失败，无法导航', icon: 'none' });
         }
       }, 1000);
     },
    
    formatPhone(phone) {
      return phone ? phone.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3') : '';
    }
  },
  onUnload() {
    if (this.map) this.map.destroy();
    if (window.initMap) delete window.initMap;
  }
};
</script>

<style lang="scss">
/* 样式与之前保持一致 */
.logistics-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 30upx;
}

.logistics-header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100upx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: relative;

  .back-btn {
    position: absolute;
    left: 30upx;
    width: 60upx;
    height: 60upx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: transparent;
    padding: 0;
    margin: 0;

    .fa {
      font-size: 32upx;
      color: #333;
    }
  }

  .title {
    font-size: 34upx;
    color: #333;
    font-weight: 500;
  }

  .empty-box {
    width: 60upx;
  }
}

.logistics-info {
  margin-top: 20upx;
  background-color: #fff;
  padding: 30upx;

  .info-item {
    display: flex;
    padding: 22upx 0;
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 28upx;
      color: #666;
      width: 200upx;
      line-height: 1.5;
    }

    .value {
      font-size: 28upx;
      color: #333;
      flex: 1;
      line-height: 1.5;
      word-break: break-all;
    }
  }
}

.map-container {
  margin-top: 20upx;
  background-color: #fff;
  padding: 20upx 30upx 30upx;

  .map-title {
    font-size: 30upx;
    color: #333;
    margin-bottom: 20upx;
    font-weight: 500;
  }

  .map-wrapper {
    width: 100%;
    height: 400upx;
    border-radius: 10upx;
    overflow: hidden;
    box-shadow: 0 2upx 10upx rgba(0, 0, 0, 0.05);
  }

  .nav-btn {
    width: 100%;
    height: 80upx;
    line-height: 80upx;
    background-color: #007aff;
    color: #fff;
    font-size: 30upx;
    border-radius: 40upx;
    margin-top: 20upx;
    box-shadow: 0 4upx 10upx rgba(0, 122, 255, 0.3);
    border: none;

    &::after {
      border: none;
    }
  }
}
</style>